<template>
  <div class="pad-btn content">
    <div class="bill-list box box-ver">
      <div  v-for="(item, index) in detailList" :value="item" :key="index" class="bill-item box box-ver">
        <div class="bill-content box box-ver">
           <div class="payee box">{{item.payee}}</div>
           <div class="info box">
             <div class="fee">金额：{{(item.user_info.fee/100).toFixed(2)}}</div>
             <div class="billing_time">&nbsp;&nbsp;时间：{{item.user_info.billing_time | Ftime}}</div>
           </div>
           <div class="title box">
             抬头&nbsp;&nbsp;{{item.user_info.title}}
           </div>
        </div>
        <div class="tag-container box box-ver">
          <div class="box tx-l">请选择报销类别</div>
          <div class="tag-list box box-pc w-p100">
            <div @click="changeTag(index,index1,'businessType')" :class="{act:item1.id==item.tagId}" :value="item1" :key="index1"  v-for="(item1, index1) in businessType.list" class="animated tag-item tx-c box box-ac box-pc">{{item1.name}}</div>
          </div>
        </div>
      </div>
    </div>
    <div  @click="saveInvoice()" class="btn-bot">导入</div>
  </div>
</template>

<script>
import { formatDate } from '@/assets/js/common'
import { openToast } from '@/assets/js/tools'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      detailList: [],
      businessType: {
        checkedId: '',
        list: [{
          name: '住宿费',
          id: 1
        }, {
          name: '餐饮费',
          id: 2
        }, {
          name: '通讯费',
          id: 3
        }, {
          name: '其他',
          id: 4
        }]
      }
    }
  },
  mounted () {
    this.getBillDetail()
  },
  computed: mapState(['userNum']),
  filters: {
    Ftime (time) {
      let date = new Date(time * 1000)
      return formatDate(date, 'yyyy-MM-dd')
    }
  },
  methods: {
    getBillDetail () {
      let _this = this
      let chooseInvoiceInfo = this.$store.state.chooseInvoiceInfo
      let data = {
        jsons: JSON.stringify({
          item_list: chooseInvoiceInfo
        })
      }
      console.log('获取发票详情', JSON.stringify(data))
      this.$http({
        method: 'post',
        url: `/vank/receipt/details1.do`,
        data: data
      }).then(res => {
        let data = JSON.parse(res.data)
        if (data.errcode === 0) {
          let itemList = data.item_list
          itemList.forEach((item, index) => {
            itemList[index].tagId = ''
          })
          console.log(itemList)
          _this.detailList = itemList
        }
      })
    },
    saveInvoice () {
      let _this = this
      let hasSaveLen = 0
      let invoiceLen = _this.detailList.length
      let hasCheckedTagLen = 0
      _this.detailList.forEach((item, index) => {
        if (item.tagId) hasCheckedTagLen++
      })
      // _this.updatestatusbatch(_this.detailList[0])
      if (hasCheckedTagLen !== _this.detailList.length) {
        openToast({
          msg: '存在未选择报销类别的发票',
          duration: 2000
        })
        return
      }
      _this.detailList.forEach((item, index) => {
        _this.$http({
          type: 'XML',
          method: 'post',
          url: this.$config.api.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
          data: {
            servername: 'saveInvoice',
            data: {
              useraccount: this.userNum,
              invoicecode: item.user_info.billing_no,
              invoicenum: item.user_info.billing_code,
              invoicedate: formatDate(new Date(item.user_info.billing_time * 1000), 'yyyy-MM-dd'),
              invoiceamount: (item.user_info.fee_without_tax / 100).toFixed(2),
              totalamount: (item.user_info.fee / 100).toFixed(2),
              detailedtype: item.tagId,
              datasource: 2,
              pdfuuid: '', // item.user_info.pdf_url
              checkresult: '', // 1 - 已核验
              gfnsrsbh: item.user_info.buyer_number,
              gfname: item.user_info.title,
              xfnsrsbh: item.user_info.seller_number,
              xfname: item.payee,
              tnvoicetype: 10,
              machinecode: '',
              fpjym: item.user_info.check_code,
              filepath: encodeURIComponent(item.user_info.pdf_url),
              invoicekey: ''
            }
          }
        }).then(data => {
          if (+data.result['#text'] === 0) {
            // hasSaveLen++
            // if (hasSaveLen === invoiceLen) {
            //   _this.$router.replace('/myInvoice')
            // }
            // 更新发票状态
            _this.updatestatusbatch(_this.detailList[hasSaveLen], () => {
              if (hasSaveLen === invoiceLen) {
                _this.$router.replace('/invoice')
              }
            })
            hasSaveLen++
          }
        })
      })
    },
    updatestatusbatch (item, cb) {
      let _this = this
      let encryptCode
      this.$store.state.chooseInvoiceInfo.forEach((item1, index) => {
        if (item1.card_id === item.card_id) {
          encryptCode = item1.encrypt_code
        }
      })
      let paramsJson = {
        openid: item.openid,
        reimburse_status: 'INVOICE_REIMBURSE_LOCK', // 锁定
        invoice_list: [
          {
            card_id: item.card_id,
            encrypt_code: encryptCode
          }
        ]
      }
      console.log('chooseInvoiceInfo>>>', this.$store.state.chooseInvoiceInfo)
      console.log('paramsJson>>>', JSON.stringify(paramsJson))
      _this.$http({
        method: 'post',
        url: `/vank/receipt/update1.do`,
        data: {
          paramsJson: JSON.stringify(paramsJson)
        }
      }).then(res => {
        console.log('开始锁定>>', res)
        if (+res.status === 0) {
          let data = JSON.parse(res.data)
          if (+data.errcode === 0) {
            // 锁定成功
            paramsJson.reimburse_status = 'INVOICE_REIMBURSE_CLOSURE'
            _this.$http({
              method: 'post',
              url: `/vank/receipt/update1.do`,
              data: {
                paramsJson: JSON.stringify(paramsJson)
              }
            }).then(res => {
              console.log('开始核销>>', res)
              if (+res.status === 0) {
                let data = JSON.parse(res.data)
                if (+data.errcode === 0) {
                  // 核销成功而
                  if (cb) cb()
                } else {
                  openToast({
                    msg: data.errmsg,
                    duration: 2000
                  })
                }
              }
            })
          } else {
            openToast({
              msg: data.errmsg,
              duration: 2000
            })
          }
        }
      })
    },
    changeTag (index, index1, data) {
      // console.log(this[data].list[index1].id)
      this.$set(this.detailList[index], 'tagId', this[data].list[index1].id)
      // this.detailList[index].tagId = this[data].list[index1].id
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/config';
@import '../assets/css/mixins';
.content{
  z-index:2
}
.bill-item{
  padding:.26rem .3rem .26rem .3rem;
  margin-bottom:.2rem;
  background-color: #FFF;
  .bill-content{
    border: 1px solid #d9d9d9;
    padding:.32rem .64rem .32rem .64rem;
    .payee{
      font-size:.36rem;
    }
    .info{
      margin-top:.2rem;
      .fee,.billing_time{
        font-size:.26rem;
      }
    }
    .title{
      margin-top:.2rem;
      padding-top:.2rem;
      font-size:.26rem;
      color:#727272;
      border-top:1px dashed #d9d9d9;
    }
  }
  .tag-container{
    padding-top:.26rem;
    /*标签列表*/
    .tag-list{
      padding-top:.2rem;
      .tag-item{
        border:1px solid #666;
        color:#666;
        height:.54rem;
        line-height:.54rem;
        width:1.18rem;
        font-size:.26rem;
        margin:0 .08rem;
        @include bg-size(100% 100%);
        &.act{
          // @extend .tada;
          animation-name: pulse;
          // @extend .rubberBand;
          color:$themeColor;
          border-color:$themeColor;
          @include bg-image('../assets/images/icon-tag-act');
        }
      }
    }
  }
}
.btn-bot{
  position: absolute;
  color:#FFF;
  font-size:.32rem;
  width:100%;
  bottom:0;
  left:0;
  background-color:$themeColor;
  height:1rem;
  text-align: center;
  line-height: 1rem;
}
</style>
